import { pathJoin, readFile } from '@/services/fs';
import { FormInstance, Card, Button } from 'antd';
import { getCommandKey, parseJsonConfig } from '@/utils';
import { useRequest } from 'ahooks';
import React, { useEffect, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import { insertProject, queryCateList } from '@/services';
import { message } from '@tauri-apps/api/dialog';
import windowManager from '@/utils/WindowManager';
import { WinEnums } from '@/utils/enums';

import './index.less';
import { emit } from '@tauri-apps/api/event';

const BatchImport: React.FC<any> = function () {
  const [formsMap] = useState<Map<string, FormInstance>>(new Map());
  const [cateList, setCateList] = useState<CateItem[]>([]);
  const [proList, setProList] = useState<(ProjectItem & { key: string })[]>([]);

  // 保存项目配置
  const { runAsync: save, loading: submitLoading } = useRequest(insertProject, {
    manual: true,
  });

  // 获取分类列表
  useRequest(queryCateList, {
    onSuccess(ret: any) {
      if (ret) {
        setCateList(ret || []);
      }
    },
  });

  const getProListByPaths = async (pathList: string[]) => {
    const proList = await Promise.all(
      pathList.map(async (path) => {
        const file = (await readFile(
          await pathJoin(path, 'package.json'),
        )) as string;
        const { name, description, commandList } = parseJsonConfig(file, path);
        return {
          name,
          key: path,
          code: name,
          description,
          commands: commandList,
          workSpace: path,
        };
      }),
    );
    setProList(proList);
  };

  // 提交项目配置
  const submitProject = (form?: FormInstance) =>
    new Promise(async (resolve) => {
      form
        ?.validateFields()
        .then((params) => {
          console.log(51, params);
          const { commands } = params;
          commands.forEach((cmd: CommandItem) => {
            cmd.key = getCommandKey(params.code, cmd.value);
          });
          save(params)
            .then(() => {
              emit('flushProjectList');
              resolve(true);
            })
            .catch((e) => {
              message(e.message, {
                title: '提示',
                type: 'error',
              });
              resolve(false);
            });
        })
        .catch(() => {
          resolve(false);
        });
    });

  /*批量导入 */
  const batchImport = async () => {
    const formKeys = Array.from(formsMap.keys());
    const newProList = formKeys.map((key) => {
      const index = proList.findIndex((pro) => pro.key === key);
      const values = formsMap.get(key)?.getFieldsValue();
      return { ...proList[index], ...values };
    });
    setProList(newProList);
    let i = 0;
    while (i < formKeys.length) {
      const key = formKeys[i];
      const form = formsMap.get(key);
      const ret = await submitProject(form);
      if (!ret) break;
      else {
        formsMap.delete(key);
        const index = proList.findIndex((pro) => pro.key === key);
        proList.splice(index, 1);
        setProList([...proList]);
      }
      i++;
    }
    if (formsMap.size === 0) {
      windowManager.closeWin(WinEnums.IMPORT_WIN);
      await message('导入完成', {
        title: '提示',
        type: 'info',
      });
    }
  };

  useEffect(() => {
    formsMap.clear();
    const dirList = JSON.parse(localStorage.getItem('init-import-win') || '[]');
    if (dirList.length > 0) {
      getProListByPaths(dirList);
    } else {
      setProList([]);
    }
  }, []);
  return (
    <Card
      title="批量导入"
      className="batch-import-card"
      extra={
        <Button type="primary" onClick={batchImport}>
          导入
        </Button>
      }
      loading={submitLoading}
    >
      {proList.map((proData, i) => (
        <div key={proData.key}>
          <h3>
            项目{i + 1}
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={async () => {
                formsMap.delete(proData.key);
                proList.splice(i, 1);
                setProList([...proList]);
                if (proList.length === 0) {
                  message('无可导入项目', {
                    title: '提示',
                    type: 'info',
                  });
                  windowManager.closeWin(WinEnums.IMPORT_WIN);
                }
              }}
            >
              删除
            </Button>
          </h3>
          <CreateForm
            cateList={cateList}
            onLoad={(form) => formsMap.set(proData.key as string, form)}
            data={proData}
          />
        </div>
      ))}
    </Card>
  );
};

export default BatchImport;
